package com.example.newfragemnt;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import java.util.ArrayList;

public class NewListFragment extends Fragment implements AdapterView.OnItemClickListener {
    private FragmentManager fManager;
    private ArrayList<Data> datas;
    private  ListView list_news;

    public NewListFragment(FragmentManager fManager, ArrayList<Data> datas) {
        this.fManager = fManager;
        this.datas = datas;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        //得到fragment的视图
        View view = inflater.inflate(R.layout.fg_newlist,null);
        //得到ListView
        list_news = view.findViewById(R.id.list_news);
        //必须设置适配器
        //getActivity()她所得到就是我们当前主窗口 MainActivity1
        MyAdapter md = new MyAdapter(datas,getActivity());
        list_news.setAdapter(md);
        //要为当前这个显示新闻标题的Listview，添加条目点击事件
        list_news.setOnItemClickListener(this);
        return view;
    }

    @Override
    //当点击ListView里面的条目的时候就会自动调用此方法，条目点击操作方法
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //得到显示新闻内容的fragment
        FragmentTransaction ft = fManager.beginTransaction();

      NewContentFragment contentFragment = new NewContentFragment();

        //要将NewListFragment中的数据（新闻内容）传到NewContentFragment里面去
        //数据绑定器
        Bundle bundle = new Bundle();
        //数据帮顶器设置
        bundle.putString("content",datas.get(position).getNew_content());
        //这就是往NewContentFragment里面绑定值
        contentFragment.setArguments(bundle);
        //要将Activity中的frameLayout这个容器中的NewListFragment替换成NewContentFragment
        ft.replace(R.id.fl_content,contentFragment);

        //记得将contentFragment这个fragment放到栈中去
        ft.addToBackStack(null);
        //提价事物

        ft.commit();
    }
}
